﻿using System;

namespace ContainerHost.ServiceModel
{
    /// <summary>
    /// Custom service host which keeps a reference to an IContainer for type resolution.
    /// </summary>
    public class ContainerServiceHost : System.ServiceModel.ServiceHost
    {
        #region Properties
        public IContainer Container { get; set; }
        #endregion

        protected ContainerServiceHost()
        {
            Container = new DefaultContainer();
        }
        public ContainerServiceHost(Type serviceType, params Uri[] baseAddresses)
            : base(serviceType, baseAddresses)
        {
            Container = new DefaultContainer();
        }
        public ContainerServiceHost(object singletonInstance, params Uri[] baseAddresses)
            : base(singletonInstance, baseAddresses)
        {
            Container = new DefaultContainer();
        }

        public ContainerServiceHost(IContainer container, Type serviceType, params Uri[] baseAddresses) : base(serviceType, baseAddresses)
        {
            Container = container;
        }

        protected override void OnOpening()
        {
            if (Description.Behaviors.Find<Description.ContainerServiceBehavior>() == null)
            {
                Description.Behaviors.Add(new Description.ContainerServiceBehavior(Container));
            }
            base.OnOpening();

        }
    }
}
